const path = require('path');
const BaseIpcHandler = require('../BaseIpcHandler');
const BaseDatasetWrapper = require('../../labels/BaseDatasetWrapper');
const { checkDirectoryExists } = require('../../utils/fileUtils');

class CreateDatasetHandler extends BaseIpcHandler {
    async handle(event, params) {
        // 解析参数
        // console.log('>> CreateDatasetHandler params = ', params);
        const dataset_info = params;

        // 业务逻辑
        let result = null;
        try {
            // 检查 dataset_dir 目录是否存在或者是否已经被使用
            const datasetDirExists = await checkDirectoryExists(dataset_info.dataset_dir);
            if (!datasetDirExists) {
                throw { errorCode: -3, message: 'Dataset directory does not exist!' };
            }

            const isUsed = await this.app.db.datasets.isDirectoryUsed(dataset_info.dataset_type, dataset_info.dataset_dir);
            if (isUsed) {
                throw { errorCode: -4, message: 'Dataset directory has been used!' };
            }

            // 生成新dataset的id，并调用数据集解析生成列表和缓存数据
            // dataset_info.id = generateTimestampBasedID();
            BaseDatasetWrapper.invokeParse(this.app, dataset_info);
            result = { code: 0, msg: 'Start parsing dataset directory!' };
        } catch (error) {
            console.error('Create Database Failed, Error: ', error.message);
            switch (error.errorCode) {
                case -3:
                    result = { code: -3, msg: error.message };
                    break;
                case -4:
                    result = { code: -4, msg: error.message };
                    break;
                default:
                    result = { code: -1, msg: error.message };
            }
        }
        // console.log('CreateDataset result = ', result);

        // 返回结果
        // console.log('Create Database Result = ', result);
        if (event.from === 'localserver') {
            event.resp.send(result);
        } else {
            return result;
        }
    }
}

module.exports = CreateDatasetHandler;
